package com.bimeeting.top;


import java.io.*;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.*;
import java.util.Map.Entry;

/**
 * 下单demo
 */
public class ApiDemo {


    /**
     * 请求地址
     */
    private final static String HOST = "exchange.bimeeting.cn";

    /**
     * 配置你的KEY
     */
    private final static String ACCESS_KEY = "111";
    private final static String SECRET_KEY = "222";

    public static void main(String[] args) throws UnsupportedEncodingException {
        //下单
        String uri = "/api/v1/place";
        String httpMethod = "GET";
        Map<String, String> params = new HashMap<>();
        params.put("ApiKey", ACCESS_KEY);
        params.put("ApiSecret", SECRET_KEY);
        params.put("timestamp", String.valueOf(System.currentTimeMillis()));
        params.put("pair", "BTC_USDT");
        params.put("type", "buy");
        params.put("number", "1");
        params.put("price", "8000");
        params.put("sign", makeSign(params));
        doHttpRequest(HOST, uri, httpMethod, params);
    }

    public static void doHttpRequest(String host, String uri, String httpMethod, Map<String, String> params) {
        try {
            String url = "http://" + host + uri;
            if ("GET".equals(httpMethod.toUpperCase())) {
                System.out.println(get(url, params));
            } else if ("POST".equals(httpMethod.toUpperCase())) {
                System.out.println(post(url, params));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * get请求
     *
     * @param url
     * @param param
     * @return
     * @throws Exception
     */
    public static String get(String url, Map<String, String> param) throws Exception {
        StringBuilder params = new StringBuilder();
        for (Entry<String, String> entry : param.entrySet()) {
            params.append(entry.getKey());
            params.append("=");
            String value = entry.getValue();
            params.append(URLEncoder.encode(value, "UTF-8"));
            params.append("&");
        }
        if (params.length() > 0) {
            params.deleteCharAt(params.lastIndexOf("&"));
        }
        String reqUrl = url + (params.length() > 0 ? "?" + params.toString() : "");
        URL restServiceURL = new URL(reqUrl);
        HttpURLConnection con = (HttpURLConnection) restServiceURL.openConnection();
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestMethod("GET");
        return toConnection(con);
    }

    /**
     * post    请求
     *
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> params) throws Exception {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestProperty("Charset", "UTF-8");
        con.setRequestMethod("POST");
        con.setConnectTimeout(30 * 1000);
        con.setReadTimeout(100 * 1000);
        con.setDoOutput(true);
        if (params != null) {
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            StringBuffer httpParams = new StringBuffer();
            for (Entry<String, String> entry : params.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                httpParams.append(key).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
            }
            if (httpParams.length() > 0) {
                httpParams.deleteCharAt(httpParams.length() - 1);
            }
            wr.writeBytes(httpParams.toString());
            wr.flush();
            wr.close();
        }
        return toConnection(con);
    }

    public static String toConnection(HttpURLConnection con) throws Exception {
        int responseCode = con.getResponseCode();
        if (responseCode < 200 || responseCode >= 300) {
            System.out.println("Request failed:" + responseCode);
            return null;
        }
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringWriter writer = new StringWriter();
        char[] chars = new char[1024];
        int count = 0;
        while ((count = in.read(chars)) > 0) {
            writer.write(chars, 0, count);
        }
        return writer.toString();
    }

    public static String makeSign(Map<String, String> makeOrderParams) {
        SortedMap<String, String> paramsMaps = new TreeMap<>();
        for (String field : makeOrderParams.keySet()) {
            Object value = makeOrderParams.get(field);
            if (value != null) {
                String valueStr = null;
                if (value instanceof BigDecimal) {
                    valueStr = ((BigDecimal) value).stripTrailingZeros().toPlainString();
                } else {
                    valueStr = value.toString();
                }
                paramsMaps.put(field, valueStr);
            }
        }
        String signStr = makeSignStr(paramsMaps);
        return Objects.requireNonNull(MD5(signStr)).toLowerCase();
    }

    private static String makeSignStr(SortedMap<String, String> params) {
        StringBuilder stringBuilder = new StringBuilder(120);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            String value = entry.getValue();
            stringBuilder.append(entry.getKey()).append("=").append(value).append("&");
        }
        return stringBuilder.substring(0, stringBuilder.length() - 1);
    }

    public final static String MD5(String s) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = s.getBytes();
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}
